<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 给定一个非负整数数组和一个整数 m，你需要将这个数组分成 m 个非空的连续子数组。设计一个算法使得这 m 个子数组各自和的最大值最小。
      var splitArray = function (nums, m) {
        let left = 0,
          right = 0;
        let len = nums.length;
        for (let i = 0; i < len; i++) {
          right += nums[i]; //求数组之和
          if (left < nums[i]) {
            left = nums[i]; //求出最大值
          }
        }
        function check(mid, m) {
          let sum = 0;
          let cnt = 1;
          for (let i = 0; i < len; i++) {
            if (sum + nums[i] > mid) {
              cnt++;
              sum = nums[i];
              // console.log(sum)
            } else {
              sum += nums[i];
            }
          }
          return cnt <= m;
        }
        // console.log(right);//32
        // console.log(left);//10
        while (left < right) {
          let mid = Math.floor((left + right) / 2);
          if (check(mid, m)) {
            right = mid;
          } else {
            left = mid + 1;
          }
        }
        return left;
      };

      let arr = [7, 2, 5, 10, 8];
      let m = 2;
      let result = splitArray(arr, m);
      // console.log(result)
    </script>
  </body>
</html>
